<!--
 * @Description: 租户管理
 * @Author: wning
 * @Date: 2022-12-06 11:10:59
 * @LastEditors: Andy
 * @LastEditTime: 2023-01-16 20:38:49
-->

<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="handleReset">
      <x-filter-item :label="$t('system.tenant.tenantName')">
        <el-input
          v-model="searchParams.tenantName"
          :placeholder="$t('system.tenant.tenantNamePlaceholder')"
          clearable
          maxlength="100"
        ></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('system.tenant.state')">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.state"
          :options="dictOptions['system.state']"
          style="width: 100%"
          clearable
        ></x-select>
      </x-filter-item>
    </x-filter>
    <!--数据面板-->
    <x-data>
      <!--数据面板按钮插糟-->
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button type="primary" v-hasPermi="['upms:tenant:add']" @click="handleAdd" :icon="buttonIcons('add')">
              {{ $t('common.add') }}
            </el-button>
            <el-button
              type="primary"
              v-hasPermi="['upms:tenant:state']"
              @click="handleChangeState(0)"
              :icon="buttonIcons('other')"
            >
              {{ $t('system.tenant.batchEnable') }}
            </el-button>
            <el-button
              type="primary"
              v-hasPermi="['upms:tenant:state']"
              @click="handleChangeState(1)"
              :icon="buttonIcons('other')"
            >
              {{ $t('system.tenant.batchDeactivation') }}
            </el-button>
            <el-button
              type="danger"
              v-hasPermi="['upms:tenant:delete']"
              @click="handleDeleteBtn"
              :icon="buttonIcons('delete')"
            >
              {{ $t('common.batchDelete') }}
            </el-button>
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" />
          </el-col>
        </el-row>
      </template>
      <!-- 数据表格 -->
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth"
          :label="item.label"
          :sortable="'custom'"
        >
          <template slot-scope="scope">
            <!-- <x-state-cell
              v-if="item.prop === 'state'"
              :stateClass="scope.row[item.prop] === 0 ? 'gray' : scope.row[item.prop] ? 'success' : ''"
              :text="scope.row[item.prop] ? selectDictLabel(stateOption, scope.row[item.prop] + '') : '-'"
            /> -->
            <el-switch
              v-if="item.prop === 'state'"
              :value="scope.row[item.prop]"
              active-color="#4474F6"
              inactive-color="#A5A9B2"
              @change="changTenantState(scope.row[item.prop], scope.row.id)"
              :disabled="!checkBntPermi('upms:tenant:state')"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :align="'center'" width="200">
          <template slot-scope="scope">
            <more-table-actions
              :action-list="actions"
              :permis-list="permissionsActions"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
    <!-- 新增 编辑 详情 -->
    <tenant-dialog ref="tenantDialog" :dict-options="dictOptions" @handleSuccess="loadData"></tenant-dialog>
    <!-- 主账号转移 -->
    <account-transfer
      ref="accountTransferDialog"
      :dict-options="dictOptions"
      @handleSuccess="loadData"
    ></account-transfer>
    <user-reset ref="tenantResetComponent" @handleResetSuccess="loadData"></user-reset>
  </x-page>
</template>
<script>
  // import { TableListMixin, QueryDictMixin, PermissionsMixin } from '@/common/mixins'
  import { selectDictLabel, buttonIcons, TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import { columns, actions } from '../config/tenant.js'
  import { tenantBathDelete, listUrl, tenantBatchDisable, tenantBatchEnable, tenantFindById } from '../api/tenant.js'
  import TenantDialog from '../components/tenantDialog.vue'
  import AccountTransfer from '../components/accountTransfer.vue'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import UserReset from '../components/userReset.vue'

  export default {
    name: 'Tenant',
    components: { TenantDialog, AccountTransfer, UserReset },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        buttonIcons,
        listUrl,
        columns,
        actions,
        searchParams: {
          tenantName: '',
          state: ''
        },
        statusOptions: [],
        tableColumns: [],
        tableData: [],
        selectionData: [],
        dictKeys: ['system.state']
      }
    },
    methods: {
      selectDictLabel,
      handleSearch(val) {
        this.queryParam = Object.assign(this.searchParams, val)
        this.loadData()
      },
      /**
       * 重置查询
       *
       */
      handleReset() {
        this.resetSearch()
      },
      async handleChangeState(state) {
        if (!this.selectionRows.length) {
          this.$message.warning('请选择操作的租户')
          return
        }
        this.$confirm(
          `${state}` === '0' ? this.$t('system.tenant.enableTips') : this.$t('system.tenant.disableTips'),
          this.$t('system.tenant.tips'),
          {
            confirmButtonText: this.$t('common.sure'),
            cancelButtonText: this.$t('common.cancel')
          }
        )
          .then((confirm) => {
            const ids = this.selectionRows.map((v) => v.id)

            this.changTenantState(state, ids)
          })
          .catch((cancel) => {})
      },
      async changTenantState(state, ids) {
        const result = Array.isArray(ids) ? ids : [ids]
        const { code } = `${state}` === '1' ? await tenantBatchDisable(result) : await tenantBatchEnable(result)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.loadData()
        } else {
          this.$message.error(msg)
        }
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'delete':
            this.$confirm('确认删除租户吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then((confirm) => {
                this.handleDelete(data.id)
              })
              .catch((cancel) => {})
            break
          case 'edit':
            this.$refs.tenantDialog.handleOpen(data)
            break
          case 'assignMenu':
            tenantFindById(data.id).then(({ data }) => {
              this.$router.push({ path: '/system/tenant/assignMenu', query: { param: JSON.stringify(data) } })
            })
            break
          case 'accountTransfer':
            tenantFindById(data.id).then(({ data }) => {
              this.$refs.accountTransferDialog.handleOpen(data)
            })
            break
          case 'resetPassword':
            this.$refs.tenantResetComponent.handleOpen({ id: data.adminUserId })
            break
        }
      },
      //   新增
      handleAdd() {
        this.$refs.tenantDialog.handleOpen({
          state: 1
        })
      },
      /**
       * 批量删除
       *
       */
      handleDeleteBtn() {
        // this.selectionData = [{id:1},{id:2}]
        if (this.selectionData.length == 0) {
          this.$message.error(this.$t('system.tenant.selectionDataMin'))
        } else {
          const ids = this.selectionData
            .map((item) => {
              return item.id
            })
            .toString()
          this.$confirm(this.$t('system.tenant.enableDelete'), this.$t('system.tenant.tips'), {
            confirmButtonText: this.$t('common.sure'),
            cancelButtonText: this.$t('common.cancel')
          })
            .then((confirm) => {
              this.handleDelete(ids)
            })
            .catch((cancel) => {})
        }
      },
      /**
       * 删除接口
       *
       */
      handleDelete(infoId) {
        tenantBathDelete(infoId).then((res) => {
          if (res.code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.deleteSuccess'))
          } else {
            this.$message.error(res.msg)
          }
          this.loadData()
        })
      }
    }
  }
</script>
